package basic.study.wantOffer.chapter5;

import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

/**
 * @ClassName Problem51
 * @Description 数组中的逆序对
 * @Company inspur
 * @Author Kevin
 * @Date 2020/6/6 14:17
 * @Version 1.0
 */
public class Problem51 {
    /**
     * 做法：归并排序，边归并排序边统计
     */
    public static int inversePairs(int[] arr) {
        if (arr == null || arr.length == 0) {
            return 0;
        }
        int count = getCount(arr, 0, arr.length-1);
        return count;
    }

    private static int getCount(int[] arr, int start, int end) {
        int count = 0;
        int left = 0;
        int right = 0;
        int mid = start + (end - start) >> 1;
        if (start < end) {
            left = getCount(arr, start, mid);
            right = getCount(arr, mid + 1, end);
            int[] temp = new int[end - start + 1];
            //从末尾开始的指针
            int p1 = mid;
            int p2 = end;
            int p3 = end - start;//temp数组指针
            while (p1 >= start && p2 >= mid+1) {
                if (arr[p1] > arr[p2]) {
                    count += (p2 - mid);
                    temp[p3] = arr[p1--];
                } else {
                    temp[p3] = arr[p1--];
                }
                p3--;
            }
            while (p1 >= start) {
                temp[p3--] = arr[p1--];
            }
            while (p2 >= mid+1) {
                temp[p3--] = arr[p2--];
            }
            //赋值回去内部排序完毕的数组
            for (int i = 0; i < temp.length; i++) {
                arr[start + i] = temp[i];
            }
        }
        return count + left + right;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{3,2,1};
        System.out.println(inversePairs(arr));
    }
}
